<template>
  <div>
    <el-dialog
      :append-to-body="true"
      @open="openDialog"
      @close="setRolesDialogClosed"
      title="角色授权"
      :visible.sync="dialogVisible"
      width="800px"
    >
      <el-tree
        :default-expand-all="true"
        :data="UserRightsList"
        show-checkbox
        node-key="id"
        :default-checked-keys="defkey"
        :props="defaultProps"
        ref="ruleTree"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changRuleTree">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllUserRightsApi,
  postUserRollApi
} from '@/Utils/Api/getUserRightApi'
export default {
  name: 'changUserRight',
  data () {
    return {
      dialogVisible: false,
      role: [],
      UserRightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      defkey: []
    }
  },
  components: {},
  created () {},
  mounted () {},
  methods: {
    // 弹窗打开时发生的事件
    openDialog () {
      this.getAllUserRights()
      this.getTerNodeKey(this.role, this.defkey)
    },
    // 获得所有权限
    async getAllUserRights () {
      const { data } = await getAllUserRightsApi('tree')
      if (data.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: data.meta.msg
        })
      }
      this.UserRightsList = data.data
      this.$message({
        type: 'success',
        message: data.meta.msg
      })
      console.log(data)
    },
    // 获取三级权限节点
    getTerNodeKey (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getTerNodeKey(item, arr)
      })
    },
    // 修改角色权限
    async changRuleTree () {
      const newKeys = [
        ...this.$refs.ruleTree.getHalfCheckedKeys(),
        ...this.$refs.ruleTree.getCheckedKeys()
      ]
      const idStr = newKeys.join(',')
      const { data } = await postUserRollApi(this.role.id, { rids: idStr })
      if (data.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: data.meta.msg
        })
      }
      this.$message({
        type: 'success',
        message: data.meta.msg
      })
      this.$emit('changeRoleInfoDrive')

      this.dialogVisible = false
    },
    // 关闭窗口时触发的事件
    setRolesDialogClosed () {
      this.defkey = []
    }
  },
  computed: {},
  watch: {}
}
</script>

<style scoped>
</style>
